import { useEffect, useMemo, useState } from 'react';
import { useAuth } from '@/auth/context/auth-context';
import { zodResolver } from '@hookform/resolvers/zod';
import {
  AlertCircle,
  Check,
  Eye,
  EyeOff,
  Loader2,
} from 'lucide-react';
import { useForm } from 'react-hook-form';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { Alert, AlertIcon, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import {
  getChangePasswordSchema,
  getResetPasswordWithTokenSchema,
} from '../forms/reset-password-schema';

export function ChangePasswordPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { resetPassword, changePassword } = useAuth();
  const [passwordVisible, setPasswordVisible] = useState(false);
  const [confirmPasswordVisible, setConfirmPasswordVisible] = useState(false);
  const [isProcessing, setIsProcessing] = useState(false);
  const [error, setError] = useState(null);
  const [successMessage, setSuccessMessage] = useState(null);

  const token =
    searchParams.get('token') ||
    searchParams.get('code') ||
    searchParams.get('token_hash');

  const [mode, setMode] = useState(token ? 'reset' : 'change');

  useEffect(() => {
    if (token) {
      setMode('reset');
    }
  }, [token]);

  const schema = useMemo(
    () =>
      mode === 'reset'
        ? getResetPasswordWithTokenSchema(Boolean(token))
        : getChangePasswordSchema(),
    [mode, token],
  );

  const form = useForm({
    resolver: zodResolver(schema),
    defaultValues:
      mode === 'reset'
        ? {
            token: token || '',
            password: '',
            confirmPassword: '',
          }
        : {
            currentPassword: '',
            newPassword: '',
            confirmPassword: '',
          },
  });

  useEffect(() => {
    form.reset(
      mode === 'reset'
        ? {
            token: token || '',
            password: '',
            confirmPassword: '',
          }
        : {
            currentPassword: '',
            newPassword: '',
            confirmPassword: '',
          },
    );
    setError(null);
    setSuccessMessage(null);
  }, [mode, token, form]);

  async function onSubmit(values) {
    try {
      setIsProcessing(true);
      setError(null);

      if (mode === 'reset') {
        const tokenValue = token || values.token;
        if (!tokenValue) {
          throw new Error('缺少重置令牌，请重新申请密码重置。');
        }
        await resetPassword({ token: tokenValue, newPassword: values.password });
        setSuccessMessage('密码重置成功，请使用新密码重新登录。');
        setTimeout(() => {
          navigate('/auth/signin');
        }, 2000);
      } else {
        await changePassword({
          currentPassword: values.currentPassword,
          newPassword: values.newPassword,
        });
        setSuccessMessage('密码修改成功。');
        form.reset({
          currentPassword: '',
          newPassword: '',
          confirmPassword: '',
        });
      }
    } catch (err) {
      console.error('Password reset error:', err);
      setError(
        err instanceof Error
          ? err.message
          : 'An unexpected error occurred. Please try again.',
      );
    } finally {
      setIsProcessing(false);
    }
  }

  return (
    <div className="max-w-md mx-auto">
      <div className="mb-6 flex flex-col gap-2">
        <h1 className="text-2xl font-bold tracking-tight">
          {mode === 'reset' ? '设置新密码' : '修改密码'}
        </h1>
        <p className="text-sm text-muted-foreground">
          {mode === 'reset'
            ? '请输入您要设置的新密码，如果手上有重置令牌也可以直接填写。'
            : '请输入当前密码与新密码，提交后立即生效。'}
        </p>
        <div className="flex gap-2 rounded-md bg-muted/40 p-1">
          <Button
            type="button"
            size="sm"
            variant={mode === 'change' ? 'default' : 'ghost'}
            onClick={() => setMode('change')}
            className="flex-1"
          >
            登录状态下修改
          </Button>
          <Button
            type="button"
            size="sm"
            variant={mode === 'reset' ? 'default' : 'ghost'}
            onClick={() => setMode('reset')}
            className="flex-1"
          >
            使用重置令牌
          </Button>
        </div>
      </div>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          {error && (
            <Alert variant="destructive">
              <AlertIcon>
                <AlertCircle className="h-4 w-4" />
              </AlertIcon>
              <AlertTitle>{error}</AlertTitle>
            </Alert>
          )}

          {successMessage && (
            <Alert>
              <AlertIcon>
                <Check className="h-4 w-4 text-green-500" />
              </AlertIcon>
              <AlertTitle>{successMessage}</AlertTitle>
            </Alert>
          )}

          {mode === 'change' && (
            <FormField
              control={form.control}
              name="currentPassword"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>当前密码</FormLabel>
                  <Input
                    placeholder="输入当前密码"
                    type="password"
                    autoComplete="current-password"
                    {...field}
                  />
                  <FormMessage />
                </FormItem>
              )}
            />
          )}

          {mode === 'reset' && !token && (
            <FormField
              control={form.control}
              name="token"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>重置令牌</FormLabel>
                  <Input
                    placeholder="请输入邮件中的重置令牌"
                    autoComplete="off"
                    {...field}
                  />
                  <FormMessage />
                </FormItem>
              )}
            />
          )}

          <FormField
            control={form.control}
            name={mode === 'change' ? 'newPassword' : 'password'}
            render={({ field }) => (
              <FormItem>
                <FormLabel>{mode === 'change' ? '新密码' : '设置新密码'}</FormLabel>
                <div className="relative">
                  <Input
                    placeholder="请设置一个安全的新密码"
                    type={passwordVisible ? 'text' : 'password'}
                    autoComplete="new-password"
                    {...field}
                  />

                  <Button
                    type="button"
                    variant="ghost"
                    mode="icon"
                    onClick={() => setPasswordVisible(!passwordVisible)}
                    className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                  >
                    {passwordVisible ? (
                      <EyeOff className="h-4 w-4" />
                    ) : (
                      <Eye className="h-4 w-4" />
                    )}
                  </Button>
                </div>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="confirmPassword"
            render={({ field }) => (
              <FormItem>
                <FormLabel>确认新密码</FormLabel>
                <div className="relative">
                  <Input
                    placeholder="再次输入新密码"
                    type={confirmPasswordVisible ? 'text' : 'password'}
                    autoComplete="new-password"
                    {...field}
                  />

                  <Button
                    type="button"
                    variant="ghost"
                    mode="icon"
                    onClick={() =>
                      setConfirmPasswordVisible(!confirmPasswordVisible)
                    }
                    className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                  >
                    {confirmPasswordVisible ? (
                      <EyeOff className="h-4 w-4" />
                    ) : (
                      <Eye className="h-4 w-4" />
                    )}
                  </Button>
                </div>
                <FormMessage />
              </FormItem>
            )}
          />

          <Button type="submit" className="w-full" disabled={isProcessing}>
            {isProcessing ? (
              <span className="flex items-center gap-2">
                <Loader2 className="h-4 w-4 animate-spin" /> Updating Password...
              </span>
            ) : (
              mode === 'reset' ? '重置密码' : '修改密码'
            )}
          </Button>

          <div className="text-center text-sm">
            <Link to="/auth/signin" className="text-primary hover:underline">
              Back to Sign In
            </Link>
          </div>
        </form>
      </Form>
    </div>
  );
}
